<template>
  <div class="vk-collapse">
    <slot></slot>  
  </div>
</template> 

<script setup lang="ts">
import {ref,provide,watch} from 'vue'
import type { NameType,CollapseProps, CollapseEmits } from './types'
import { collapseContextKey } from './types'

defineOptions({
    name: 'VkCollapse',
});

const props = defineProps<CollapseProps>()
const emits = defineEmits<CollapseEmits> ()
// 这里的activeNames是用来存储当前展开的item的name的,以name为标识;watch监听modelValue的变化
const activeNames=ref<NameType[]>(props.modelValue)
watch(()=>props.modelValue,()=>{activeNames.value = props.modelValue})

// accordion是否开启手风琴模式
if (props.accordion && activeNames.value.length>1){
    console.warn( 'accordion mode should only have one acitve item')
}


// 不开启手风琴模式activeNames.value中存在item，则删除对应的一项，否则插入对应的name
// 如果开启手风琴模式相等则清空，不等则替换
const handleItemClick = (item: NameType) => {
  let _activeNames = [...activeNames.value ]
  if (props.accordion) {
    _activeNames=[activeNames.value[0]===item?'':item]
    activeNames.value=_activeNames
  }else{
    const index = _activeNames.indexOf(item)
    if (index > -1){
      _activeNames.splice(index, 1)}
    else {
      _activeNames.push(item)
    } 
    activeNames.value = _activeNames
  }
  emits('update:modelValue', _activeNames)
  emits('change', _activeNames)
}

// provide和inject传值
provide(collapseContextKey, {
  activeNames,
  handleItemClick,
})

</script>